<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * =========================================================
 */

namespace app\api\controller;

use app\model\shop\Poster;
use app\model\shop\Shop as ShopModel;
use app\model\web\WebSite;

class Shop extends BaseApi
{

    /**
     * 基础信息
     */
    public function info()
    {
        $site_id = isset($this->params[ 'site_id' ]) ? $this->params[ 'site_id' ] : 0;
        $lat = isset($this->params[ 'lat' ]) ? $this->params[ 'lat' ] : ""; // 纬度
        $lng = isset($this->params[ 'lng' ]) ? $this->params[ 'lng' ] : ""; // 经度
        if (empty($site_id)) {
            return $this->response($this->error('', 'REQUEST_SITE_ID'));
        }
        $shop = new ShopModel();
        $field = 'site_id,expire_time,site_name,website_id,is_own,level_name,category_name,shop_status,start_time,end_time,avatar,banner,
		telephone,shop_desccredit,shop_servicecredit,shop_deliverycredit,workingtime,shop_label,
		shop_sales,address,full_address,longitude,latitude,sub_num';
        $info = $shop->getShopInfo([ [ 'site_id', '=', $site_id ] ], $field);

        if ($info['data'][ 'longitude' ] && $info['data'][ 'latitude' ] && $lng && $lat) {
            $info['data'][ 'distance' ] = round(getDistance((float) $info['data'][ 'longitude' ], (float) $info['data'][ 'latitude' ], (float) $lng, (float) $lat))/1000;
        } else {
            $info['data'][ 'distance' ] = 0;
        }

        $val                                          = $shop->transformSeckillTime($info['data']);
        $info['data']['start_time_show'] = "{$val['start_hour']}:{$val['start_minute']}";
        $info['data']['end_time_show']   = "{$val['end_hour']}:{$val['end_minute']}";

        return $this->response($info);
    }

    public function page()
    {
        $page = isset($this->params[ 'page' ]) ? $this->params[ 'page' ] : 1;
        $page_size = isset($this->params[ 'page_size' ]) ? $this->params[ 'page_size' ] : PAGE_LIST_ROWS;
        $keyword = isset($this->params[ 'keyword' ]) ? $this->params[ 'keyword' ] : '';//关键词
        $order = isset($this->params[ 'order' ]) ? $this->params[ 'order' ] : "site_id";//排序（综合、销量、信用）
        $sort = isset($this->params[ 'sort' ]) ? $this->params[ 'sort' ] : "desc";//升序、降序
        $web_city = isset($this->params[ 'web_city' ]) ? $this->params[ 'web_city' ] : "";
        $lat = isset($this->params[ 'lat' ]) ? $this->params[ 'lat' ] : ""; // 纬度
        $lng = isset($this->params[ 'lng' ]) ? $this->params[ 'lng' ] : ""; // 经度
        $website_id = $this->params[ 'website_id' ] ?? 0;
        $category_id = isset($this->params[ 'category_id' ]) ? $this->params[ 'category_id' ] : 0;
        $shop_status = isset($this->params[ 'shop_status' ]) ? $this->params[ 'shop_status' ] : 1;
        $shop = new ShopModel();
        $condition = [
            [ 'shop_status', '=', $shop_status ],
            [ 'cert_id', '<>', 0 ],
            ['shop_type','=',1],
        ];

        if (!empty($keyword)) {
            $condition[] = [ 'site_name', 'like', '%' . $keyword . '%' ];
        }
        if($website_id > 0){
            $condition[] = [ 'website_id', '=', $website_id];
        }
        if($category_id > 0){
            $condition[] = [ 'category_id', '=', $category_id];
        }
        // 非法参数进行过滤
        if ($sort != "desc" && $sort != "asc") {
            $sort = "";
        }

        // 非法参数进行过滤
        if ($order != '') {
            if ($order != "shop_sales" && $order != "shop_desccredit") {
                $order = 'site_id';
            }
            $order_by = $order . ' ' . $sort;
        } else {
            $order_by = 'is_recommend desc,sort desc,site_id desc';
        }

        // 查询是否存在城市分站
        if (addon_is_exit('city') && !empty($web_city)) {
            $website_model = new WebSite();
            $website_info = $website_model->getWebSite([ [ 'site_area_id', '=', $web_city ] ], 'site_id');
            if (!empty($website_info[ 'data' ])) {
                $order_by = "INSTR('{$website_info['data']['site_id']}', website_id) desc," . $order_by;
            }
        }
        $field  = 'site_id,site_name,category_id,shop_status,category_name,group_name,avatar,banner,shop_desccredit,shop_servicecredit,shop_deliverycredit,is_own,longitude,latitude,telephone,address,full_address,shop_label,per_head';

        $list = $shop->getShopPageList($condition, $page, $page_size, $order_by, $field);

        if (!empty($list[ 'data' ][ 'list' ])) {
            foreach ($list[ 'data' ][ 'list' ] as $k => $item) {
                if ($item[ 'longitude' ] && $item[ 'latitude' ] && $lng && $lat) {
                    $list[ 'data' ][ 'list' ][ $k ][ 'distance' ] = round(getDistance((float) $item[ 'longitude' ], (float) $item[ 'latitude' ], (float) $lng, (float) $lat))/1000;
                } else {
                    $list[ 'data' ][ 'list' ][ $k ][ 'distance' ] = 0;
                }
            }
            if ($sort=='desc'){
                // 按距离就近排序
                array_multisort(array_column($list[ 'data' ][ 'list' ], 'distance'), SORT_DESC, $list[ 'data' ][ 'list' ]);
            } else {
                // 按距离就近排序
                array_multisort(array_column($list[ 'data' ][ 'list' ], 'distance'), SORT_ASC, $list[ 'data' ][ 'list' ]);
            }

        }

        return $this->response($list);
    }

    public function recommend()
    {
        $page = isset($this->params[ 'page' ]) ? $this->params[ 'page' ] : 1;
        $page_size = isset($this->params[ 'page_size' ]) ? $this->params[ 'page_size' ] : PAGE_LIST_ROWS;
        $keyword = isset($this->params[ 'keyword' ]) ? $this->params[ 'keyword' ] : '';//关键词
        $order = isset($this->params[ 'order' ]) ? $this->params[ 'order' ] : "sort";//排序（综合、销量、信用）
        $sort = isset($this->params[ 'sort' ]) ? $this->params[ 'sort' ] : "desc";//升序、降序
        $web_city = isset($this->params[ 'web_city' ]) ? $this->params[ 'web_city' ] : "";
        $lat = isset($this->params[ 'lat' ]) ? $this->params[ 'lat' ] : ""; // 纬度
        $lng = isset($this->params[ 'lng' ]) ? $this->params[ 'lng' ] : ""; // 经度
        $website_id = $this->params[ 'website_id' ] ?? 0;
        $shop = new ShopModel();
        $condition = [
            [ 'shop_status', '=', 1 ],
            [ 'cert_id', '<>', 0 ],
            ['is_recommend','=',1],
            ['shop_type','=',1],
        ];

        if (!empty($keyword)) {
            $condition[] = [ 'site_name', 'like', '%' . $keyword . '%' ];
        }
        if($website_id > 0){
            $condition[] = [ 'website_id', '=', $website_id];
        }
        // 非法参数进行过滤
        if ($sort != "desc" && $sort != "asc") {
            $sort = "";
        }

        // 非法参数进行过滤
        if ($order != '') {
            if ($order != "shop_sales" && $order != "shop_desccredit") {
                $order = 'site_id';
            }
            $order_by = $order . ' ' . $sort;
        } else {
            $order_by = 'is_recommend desc,sort desc,site_id desc';
        }

        $field  = 'site_id,site_name,category_name,group_name,avatar,banner,shop_desccredit,shop_servicecredit,shop_deliverycredit,is_own,longitude,latitude,telephone,address,full_address,shop_label,shop_status,per_head';

        $list = $shop->getShopList($condition,$field ,$order_by,10);

        if (!empty($list[ 'data' ] )) {
            foreach ($list[ 'data' ] as $k => $item) {
                if ($item[ 'longitude' ] && $item[ 'latitude' ] && $lng && $lat) {
                    $list[ 'data' ][ $k ][ 'distance' ] = round(getDistance((float) $item[ 'longitude' ], (float) $item[ 'latitude' ], (float) $lng, (float) $lat))/1000;
                } else {
                    $list[ 'data' ][ $k ][ 'distance' ] = 0;
                }
                $list[ 'data' ][ $k ][ 'shop_label' ] = json_decode($item['shop_label'],true);
            }
        }

        return $this->response($list);
    }

    /**
     * 是否显示店铺相关功能，用于审核小程序
     */
    public function isShow()
    {
        $shop = new ShopModel();
        $res = $shop->getDevelopment();// 0 隐藏，1 显示
        return $this->response($this->success($res));
    }

    /**
     * 获取商品海报
     */
    public function poster()
    {
        if (!empty($qrcode_param)) return $this->response($this->error('', '缺少必须参数qrcode_param'));

        $qrcode_param = json_decode($this->params[ 'qrcode_param' ], true);
        $qrcode_param[ 'suid' ] = $qrcode_param[ 'suid' ] ?? 0;
        $poster = new Poster();
        $res = $poster->shop($this->params[ 'app_type' ], $this->params[ 'page' ], $qrcode_param);
        return $this->response($res);
    }


    //是否已入驻(本地生活/商城/酒店)
    public function isEnter()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $is_mall = model('shop')->getCount(['shop_type'=>0,'member_id'=>$this->member_id]);

        $is_local = model('shop')->getCount(['shop_type'=>1,'member_id'=>$this->member_id]);

        $is_hotel = model('hotel')->getCount(['member_id'=>$this->member_id]);

        $data = [
            'is_mall'=>$is_mall,
            'is_local'=>$is_local,
            'is_hotel'=>$is_hotel,
        ];

        return $this->response($this->success($data));
    }

    //店铺信息(商城/本地生活)
    public function enterInfo()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $shop_type = isset($this->params[ 'shop_type' ]) ? $this->params[ 'shop_type' ] : 0;

        $shop_model = new ShopModel();

        $condition = [
            ['shop_type','=',$shop_type],
            ['member_id','=',$this->member_id]
        ];

        $field = 'site_id,shop_type,code,site_name,category_id,category_name,group_id,group_name,member_id,shop_status,avatar,banner,
        name,mobile,start_time,end_time,province,province_name,city,city_name,district,district_name,address,full_address,longitude,
        latitude,contacts_card_electronic_2,contacts_card_electronic_3,contacts_card_no,contacts_card_name,contacts_card_type,
        contacts_card_start_time,contacts_card_end_time,settlement_bank_account_name,settlement_bank_name,settlement_bank_account_number,
        settlement_bank_type,settlement_bank_img,cert_type,business_licence_number,business_licence_number_electronic,license_time_type,
        license_start_date,license_end_date,per_head,shop_label';

        $res = $shop_model->getShopInfo($condition,$field);

        $val                                      = transformSeckillTime($res['data']);
        $res['data']['start_time_show'] = "{$val['start_hour']}:{$val['start_minute']}";
        $res['data']['end_time_show']   = "{$val['end_hour']}:{$val['end_minute']}";
        return $this->response($res);
    }


    //修改店铺信息
    public function editShop()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $site_id = isset($this->params[ 'site_id' ]) ? $this->params[ 'site_id' ] : 0;

        $apply_data = [
            'site_name' => isset($this->params[ 'site_name' ]) ? $this->params[ 'site_name' ] : '',//申请店铺名称
            'category_name' => isset($this->params[ 'category_name' ]) ? $this->params[ 'category_name' ] : '',//店铺分类名称
            'category_id' => isset($this->params[ 'category_id' ]) ? $this->params[ 'category_id' ] : '',//店铺分类id
            'group_name' => isset($this->params[ 'group_name' ]) ? $this->params[ 'group_name' ] : '',//开店套餐名称
            'group_id' => isset($this->params[ 'group_id' ]) ? $this->params[ 'group_id' ] : '',// 开店套餐ID

            "province" => isset($this->params[ 'province' ]) ? $this->params[ 'province' ] : '',
            "province_name" => isset($this->params[ 'province_name' ]) ? $this->params[ 'province_name' ] : '',
            "city" => isset($this->params[ 'city' ]) ? $this->params[ 'city' ] : '',
            "city_name" => isset($this->params[ 'city_name' ]) ? $this->params[ 'city_name' ] : '',
            "district" => isset($this->params[ 'district' ]) ? $this->params[ 'district' ] : '',
            "district_name" => isset($this->params[ 'district_name' ]) ? $this->params[ 'district_name' ] : '',
            "address" => isset($this->params[ 'address' ]) ? $this->params[ 'address' ] : '',
            "full_address" => isset($this->params[ 'full_address' ]) ? $this->params[ 'full_address' ] : '',
            "longitude" => isset($this->params[ 'longitude' ]) ? $this->params[ 'longitude' ] : '',
            "latitude" => isset($this->params[ 'latitude' ]) ? $this->params[ 'latitude' ] : '',
            "start_time" => isset($this->params[ 'start_time' ]) ? $this->params[ 'start_time' ] : '',
            "end_time" => isset($this->params[ 'end_time' ]) ? $this->params[ 'end_time' ] : '',
            "name" => isset($this->params[ 'name' ]) ? $this->params[ 'name' ] : '',
            "mobile" => isset($this->params[ 'mobile' ]) ? $this->params[ 'mobile' ] : '',
            "avatar" => isset($this->params[ 'avatar' ]) ? $this->params[ 'avatar' ] : '',
            "banner" => isset($this->params[ 'banner' ]) ? $this->params[ 'banner' ] : '',
            'contacts_card_electronic_2' => isset($this->params[ 'contacts_card_electronic_2' ]) ? $this->params[ 'contacts_card_electronic_2' ] : '',//申请人身份证正面
            'contacts_card_electronic_3' => isset($this->params[ 'contacts_card_electronic_3' ]) ? $this->params[ 'contacts_card_electronic_3' ] : '',//申请人身份证反面
            'contacts_card_no' => isset($this->params[ 'contacts_card_no' ]) ? $this->params[ 'contacts_card_no' ] : '',
            'contacts_card_name' => isset($this->params[ 'contacts_card_name' ]) ? $this->params[ 'contacts_card_name' ] : '',
            'contacts_card_type' => isset($this->params[ 'contacts_card_type' ]) ? $this->params[ 'contacts_card_type' ] : '',
            'contacts_card_start_time' => isset($this->params[ 'contacts_card_start_time' ]) ? $this->params[ 'contacts_card_start_time' ] : '',
            'contacts_card_end_time' => isset($this->params[ 'contacts_card_end_time' ]) ? $this->params[ 'contacts_card_end_time' ] : '',

            'settlement_bank_account_name' => isset($this->params[ 'settlement_bank_account_name' ]) ? $this->params[ 'settlement_bank_account_name' ] : '',//开户人
            'settlement_bank_account_number' => isset($this->params[ 'settlement_bank_account_number' ]) ? $this->params[ 'settlement_bank_account_number' ] : '',//银行卡号
            'settlement_bank_name' => isset($this->params[ 'settlement_bank_name' ]) ? $this->params[ 'settlement_bank_name' ] : '',//开户行
            'settlement_bank_type' => isset($this->params[ 'settlement_bank_type' ]) ? $this->params[ 'settlement_bank_type' ] : '',//开户行
            'settlement_bank_img' => isset($this->params[ 'settlement_bank_img' ]) ? $this->params[ 'settlement_bank_img' ] : '',//开户行

            'business_licence_number' => isset($this->params[ 'business_licence_number' ]) ? $this->params[ 'business_licence_number' ] : '',//统一社会信用码 input
            'business_licence_number_electronic' => isset($this->params[ 'business_licence_number_electronic' ]) ? $this->params[ 'business_licence_number_electronic' ] : '',//营业执照电子版

            'license_time_type' => isset($this->params[ 'license_time_type' ]) ? $this->params[ 'license_time_type' ] : 1,
            'license_start_date' => isset($this->params[ 'license_start_date' ]) ? $this->params[ 'license_start_date' ] : '',
            'license_end_date' => isset($this->params[ 'license_end_date' ]) ? $this->params[ 'license_end_date' ] : '',
            'per_head' => isset($this->params[ 'per_head' ]) ? $this->params[ 'per_head' ] : '',
            'shop_label' => isset($this->params[ 'shop_label' ]) ? $this->params[ 'shop_label' ] : '',
        ];
        /*dump($apply_data);die;
        $start_time = explode(':',$apply_data['start_time']);

        $apply_data['start_time'] = $start_time[0] * 3600 + $start_time[1] * 60;

        $end_time = explode(':',$apply_data['end_time']);

        $apply_data['end_time'] = $end_time[0] * 3600 + $end_time[1] * 60;*/

        //dump($apply_data);die;
        if (empty($apply_data['mobile'])) {
            return $this->response($this->error('', '请输入联系人手机号'));
        }
        if (!validatePhoneNumber($apply_data['mobile'])) {
            return $this->response($this->error('', '手机号有误'));
        }
        if (empty($apply_data['contacts_card_no'])) {
            return $this->response($this->error('', '请输入证件号'));
        }
        if (!validateIDCard($apply_data['contacts_card_no'])) {
            return $this->response($this->error('', '证件号无效'));
        }

        $model = new ShopModel();
        $result = $model->editShop($apply_data,[ [ 'site_id', '=', $site_id ] ]);
        return $this->response($result);
    }
}